package cn.jdy.platform.admin;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.jdy.authority.entity.User;
import cn.jdy.authority.entity.UserRole;
import cn.jdy.authority.service.SysMenuService;
import cn.jdy.authority.service.SysRoleService;
import cn.jdy.authority.service.UserRoleService;
import cn.jdy.authority.service.UserService;
import cn.jdy.framework.log.BaseLog;
import cn.jdy.framework.safe.SafeUtil;

/**
 * 系统用户登录
 *
 * @author liGan
 * @date: 2013-08-05
 */
@Controller
@RequestMapping("")
public class LoginCtrl {

	@Autowired
	protected HttpSession session;
	@Autowired
	private UserService userService;
	@Autowired
	private UserRoleService userRoleService;

	/**
   * 后台登录首页
   */
  @RequestMapping("")
  public ModelAndView index() {
    ModelAndView mv = new ModelAndView();
    Object so = session.getAttribute("user");
    if(so == null || so.equals("")) {
      mv.setViewName("/login.jsp");
    } else {
      mv.setViewName("redirect:/init.jsp");// 登陆成功页面
    }    
    return mv;
  }
	
	/**
	 * 后台用户登陆
	 *
	 * @return 
	 * {"unknown" : "系统繁忙!",
	 * "1" : "请输入您的用户名!",
	 * "2" : "请输入您的密码!",
	 * "3" : "此账号不存在!",
	 * "4" : "密码错误!",
	 * "5" : "登录错误次数超限，账号锁定!",
	 * "6" : "您的帐号处于冻结状态!",
	 * "7" : "登录超时，请重新登录!",
	 * "8" : "您的帐号处于禁用/锁定状态!",
	 * "9" : "您已成功退出系统!"
	 * };
	 * @param:用户名
	 * @param:密码
	 * @param:验证码
	 */
	@RequestMapping(value = "/userLogin", method = RequestMethod.POST)
	public ModelAndView login(String username, String password,String verifyWord) {
		ModelAndView mv = new ModelAndView();// 重新登陆界面
//		String VERIVYWORD = (String) session.getAttribute(GlobalConstant.VERIVYWORD);
		String VERIVYWORD = (String) session.getAttribute("verifyCode");
		if(username == null || "".equals(username.trim())) {// 用户名输入校验
		  mv.setViewName("/login.jsp");
			mv.addObject("msg", "请输入您的用户名!");
			return mv;
		}
		
		if(password == null || "".equals(password.trim())) {// 密码输入校验
		  mv.setViewName("/login.jsp");
      mv.addObject("msg", "请输入您的密码!");
			return mv;
		}
		
//		if((VERIVYWORD != null) && VERIVYWORD.equals(verifyWord)){
  		User user = userService.findOne("username", username);// 查询用户是否存在
  		if(user == null) {
  		  mv.setViewName("/login.jsp");
        mv.addObject("msg", "此账号不存在!");
  			return mv;
  		} else if(user.getPasswd().equals(SafeUtil.md5(password).substring(8, 16))) {
  //			String status = user.getStatus();//用户状态包括 启用、禁用、删除。01 正常、02 禁用 、03 删除、04 锁定。
  			if("01".equals(user.getStatus())) {//01 正常
  				List<UserRole> list = userRoleService.find("userid", user.getId());
  				String roleid = "";
  				for (int i = 0; i < list.size(); i++) {
  					if (list.get(i).getRoleid()
  							.equals("4028b3044de1a396014de1ba2b2e0000")
  							|| list.get(i).getRoleid()
  									.equals("ff8080814db89f0a014db8d169290000")) {
  						roleid = "0";
  					}
  				}
  				session.setAttribute("roleid", roleid);
  				session.setAttribute("user", user);
  				mv.setViewName("redirect:/init.jsp");// 登陆成功
  			} else {//当前用户已被禁用!
  			  mv.setViewName("/login.jsp");
  	      mv.addObject("msg", "您的帐号处于冻结状态!");
  				return mv;
  			}
  			return mv;
  		} else {
  		  mv.setViewName("/login.jsp");
        mv.addObject("msg", "密码错误!");
  			return mv;
  		}
//    }else{
//        mv.setViewName("/login.jsp");
//        mv.addObject("msg","请输入正确的验证码！");
//        return mv;
//    }
	}

	/**
	 * 用户退出
	 *
	 * @date 2013-08-06
	 * @author liGan
	 */
	@RequestMapping("/userLogout")
	public ModelAndView logout() {
		ModelAndView mv = new ModelAndView();
		session.removeAttribute("user");
		session.invalidate();
    mv.setViewName("/login.jsp");
    mv.addObject("msg", "您已成功退出系统!");
		return mv;
	}

	/**
	 * 修改资料
	 */
	@RequestMapping("/self")
	public ModelAndView self() {
		ModelAndView mv = new ModelAndView();
		mv.addObject("user", session.getAttribute("user"));
		mv.setViewName("/platform/self.jsp");
		return mv;
	}

	/**
	 * 修改个人资料
	 *
	 * @param user
	 * @param passwdNew
	 * @return
	 */
	@RequestMapping("/selfsave")
	@ResponseBody
	public Map<String, Object> save(User user, String passwdNew) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		User userOld = (User) session.getAttribute("user");
		try {
			if(userOld != null && userOld.getPasswd().equals(SafeUtil.md5(user.getPasswd()).substring(8, 16))) {
				// 只修改密码字段
				userService.update(userOld.getId(), "passwd", SafeUtil.md5(passwdNew).substring(8, 16));

				jsonMap.put("info", "修改成功！");
				jsonMap.put("statusCode", 200);
			} else {
				jsonMap.put("info", "原密码输入错误！");
				jsonMap.put("statusCode", 500);
			}
		} catch(Exception e) {
			BaseLog.e(getClass(), "用户修改资料异常", e);
			jsonMap.put("info", "系统异常！");
			jsonMap.put("statusCode", 500);
		}

		return jsonMap;
	}

}
